package mk.company.fin.structure;

import java.util.Collections;
import java.util.List;

import mk.company.fin.model.Konto;
import mk.company.fin.utils.CoreUtils;

import org.apache.commons.lang.StringUtils;


public class SearchTree {

	private SearchTreeElement root;
	
	public SearchTree() {
		root = new SearchTreeElement();
	}
	
	
	/**
	 * Add the konto to the structure.
	 * @param konto the konto to add.
	 */
	public void addKonto(Konto kontoModel) {
		// init
		String konto = kontoModel.getKonto();
		SearchTreeElement element = root;
		
		// go char by char
		for (int i = 0; i < konto.length(); i++) {
			int kontoCharMappingCode = CoreUtils.getKontoCharMappingCode(konto.charAt(i));
			element.initElement(kontoCharMappingCode);
			element.addSimilar(kontoModel);
			element = element.getElement(kontoCharMappingCode);
		}
		element.addSimilar(kontoModel);
		element.setValue(kontoModel);
	}
	
	
	/**
	 * Searches the structure for the given konto.
	 * @param konto the konto string
	 * @return the model if found
	 */
	public Konto searchKonto(String konto) {
		// init
		Konto result = null;
		SearchTreeElement element = root;
		
		// search
		if (StringUtils.isNotEmpty(konto)) {
			for (int i = 0; i < konto.length(); i++) {
				int kontoCharMappingCode = CoreUtils.getKontoCharMappingCode(konto.charAt(i));
				element = element.getElement(kontoCharMappingCode);
				if (element == null) {
					break;
				}
			}
			
			// form result
			if (element != null && element.isValid()) {
				result = element.getValue();
			}
		}
		
		// result
		return result;
	}
	
	public List<Konto> searchSimilar(String konto) {
		// init
		List<Konto> result = null;
		SearchTreeElement element = root;
		
		// search
		if (StringUtils.isNotEmpty(konto)) {
			for (int i = 0; i < konto.length(); i++) {
				int kontoCharMappingCode = CoreUtils.getKontoCharMappingCode(konto.charAt(i));
				element = element.getElement(kontoCharMappingCode);
				if (element == null) {
					break;
				}
			}
			
			// form result
			if (element != null) {
				result = element.getSimilar();
			} else {
				result = Collections.emptyList();
			}
			
		} else {
			result = Collections.emptyList();
		}
		
		// result
		return result;
	}
	
}
